<?php

class DefaultController extends CController
{
	public $layout='//layouts/install';
	public $h1='';
	
	public function init()
	{
		if (INSTALL_MODULE_DONE)
		{
			$this->redirect(array('/'));
		}
		Yii::app()->theme = param('adminTheme');
		parent::init();
	}

	
	public function actionIndex()
	{
		// licence agreement
		$license = file_get_contents(Yii::app()->modulePath.DIRECTORY_SEPARATOR.'install'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'LICENSE');
		$this->render('index', array('license'=>$license));
	}
	
	public function actionDatabase()
	{
		$model=new DatabaseForm;
		if(isset($_POST['DatabaseForm']))
		{
			$model->attributes=$_POST['DatabaseForm'];
			if($model->validate())
			{
				try
				{
                    $connectionString = "mysql:host={$model->host};dbname=".$model->database;
                    $connection = new CDbConnection($connectionString, $model->username, $model->password);
                    $connection->connectionString = $connectionString;
                    $connection->username = $model->username;
                    $connection->password = $model->password;
                    $connection->emulatePrepare = true;
                    $connection->charset = 'utf8';
                    $connection->tablePrefix = $model->prefix;
                    $connection->active = true;
					
					$db_file = Yii::app()->basePath.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'include'.DIRECTORY_SEPARATOR.'db.php';
					$db_file_tpl = Yii::app()->modulePath.DIRECTORY_SEPARATOR.'install'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'db.default.php';

					$db_data = file_get_contents($db_file_tpl);
					$db_data = str_replace(
						array('{{host}}','{{database}}','{{username}}','{{password}}','{{prefix}}'),
						array($model->host, $model->database, $model->username, $model->password, $model->prefix),
						$db_data
					);

					if (is_file_writable($db_file))
					{
						file_put_contents($db_file, $db_data);
						$this->redirect(array('modules'));
					}
					else
					{
						$model->addError('', 'File '.$db_file.' is not writable');
					}
				}
				catch (Exception $e)
				{
					$model->addError('', $e->getMessage());
				}
			}
		}
		$this->render('database',array('model'=>$model));
	}
	
	public function actionModules()
	{
		/* start install modules
		 * get all modules
		 * - install all independent modules
		 * - install one by one if installed required modules
		 * 
		 * Steps:
		 * 0. check required modules (if installing separate module)
		 * 1. update config/modules.php file
		 * 2. update config/import.php file
		 * 3. install schema
		 * 4. install data
		 * 5. insert into modules table
		 * 6. return TRUE
		*/
		$modules = array();
		if ($handle = opendir(Yii::app()->modulePath))
		{
			while (false !== ($file = readdir($handle)))
			{
				if ($file != "." && $file != ".." && $file != ".svn" && $file != "install")
				{
					$filename = Yii::app()->modulePath . DIRECTORY_SEPARATOR . $file;
					if (is_dir($filename))
					{
						$modules[] = $file;
					}
				}
			}
		}
		Yii::app()->cache->set('modulesQueue', $modules);
		Yii::app()->cache->set('modulesQueueDisabled', array());

		$progressStep = 100 / count($modules);
		
		$model = new Install();
		$model->installCoreTables();
		
		$this->render('modules', array('progressStep'=>$progressStep));
	}
	
	public function actionAjaxStart()
	{
		$response = array();
		$model = new Install();
		$modules = Yii::app()->cache->get('modulesQueue');
		$found = false;
		
		while (!$found)
		{
			if (empty($modules))
			{
				break;
			}
			else
			{
				$module = array_shift($modules);
				$check = $model->checkDependencies($module, $modules);
				if ($check['result'] === Install::REQUIRED_INSTALLED)
				{
					$found = true;
					Yii::app()->cache->set('modulesQueue', $modules);
				}
				else if ($check['result'] === Install::REQUIRED_EXISTS)
				{
					/* required module exist, wait untill installed */
					$modules[] = $module;
					Yii::app()->cache->set('modulesQueue', $modules);
				}
				else if ($check['result'] === Install::REQUIRED_NOT_FOUND)
				{
					/* required module doesn't exist, drop current module*/
					$modulesDisabled = Yii::app()->cache->get('modulesQueueDisabled');
					$modulesDisabled[] = array('module'=>$module, 'required'=>$check['required']);
					Yii::app()->cache->set('modulesQueueDisabled', $modulesDisabled);
				}
			}
		}

		if ($found)
		{
			$response['html'] = $this->renderPartial('ajaxstart', array('module'=>$module), true, true);
		}
		else
		{
			$response['html'] = $this->renderPartial('ajaxfinish', array(), true, true);
			
			$modulesDisabled = Yii::app()->cache->get('modulesQueueDisabled');
			if (!empty($modulesDisabled))
			{
				foreach ($modulesDisabled as $module => $required)
				{
					$response['error'][] = "Install ".$module['module']." module failed! Missing required modules: ".implode(', ',$module['required']);
				}
			}
		}
			
		$response['module'] = $module;
		
		echo json_encode($response);
	}
	
	public function actionAjaxSetAutoload($module)
	{
		$response = array();
		$config = Install::getModuleInstaller($module)->config();
		
		/* begin update modules file*/
		$modulesFile = Yii::app()->basePath.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'include'.DIRECTORY_SEPARATOR.'modules.php';
		$modulesArray = require($modulesFile);
		$modulesArray = (in_array($config['name'], $modulesArray)) ? $modulesArray : array_merge($modulesArray, (array)$config['name']);
		$modulesArrayContent = "<?php\n";
		$modulesArrayContent .= "return ";
		$modulesArrayContent .= array2print($modulesArray);
		$modulesArrayContent .= ";\n";
		$modulesArrayContent .= "?>";
		if (is_file_writable($modulesFile))
		{
			file_put_contents($modulesFile, $modulesArrayContent);
		}
		else
		{
			$response['error'][] = "Check permissions for /protected/config/modules.php";
		}
		/* end update modules file*/

		/* begin update import file*/
		$importFile = Yii::app()->basePath.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'include'.DIRECTORY_SEPARATOR.'import.php';
		$importArray = require($importFile);
		if (isset($config['import']) && is_array($config['import']))
		{
			$importArray = array_unique(array_merge($importArray, $config['import']));
			$importArrayContent = "<?php\n";
			$importArrayContent .= "return ";
			$importArrayContent .= array2print($importArray);
			$importArrayContent .= ";\n";
			$importArrayContent .= "?>";
			if (is_file_writable($importFile))
			{
				file_put_contents($importFile, $importArrayContent);
			}
			else
			{
				$response['error'][] = "Check permissions for /protected/config/include/import.php";
			}
		}
		/* end update import file*/
		
		$response['html'] = $this->renderPartial('ajaxsetautoload', array('module'=>$module), true, true);
		echo json_encode($response);
	}
	
	public function actionAjaxInstallDatabase($module)
	{
		$response = array();
		$class = Install::getModuleInstaller($module);
		
		if (method_exists($class, 'install'))
			$class->install();
		
		$response['html'] = $this->renderPartial('ajaxinstalldatabase', array('module'=>$module), true, true);
		
		echo json_encode($response);
	}
	
	public function actionAjaxFinishModule($module)
	{
		$response = array();
		$config = Install::getModuleInstaller($module)->config();
		
		$model = new Install();
		$model->updateModulesTable($config);
		
		$response['html'] = $this->renderPartial('ajaxfinishmodule', array('module'=>$module), true, true);
		
		$modules = Yii::app()->cache->get('modulesQueue');
		if (!empty($modules))
		{
			$response['finish'] = false;
		}
		else
		{
			$response['finish'] = true;
			
			$modulesDisabled = Yii::app()->cache->get('modulesQueueDisabled');
			if (!empty($modulesDisabled))
			{
				foreach ($modulesDisabled as $module)
				{
					$response['error'][] = "Install ".$module['module']." module failed! Missing requierd modules: ".implode(', ',$module['required']);
				}
			}
		}
		
		echo json_encode($response);
	}
	
	public function actionSiteSettings()
	{
		Yii::import('application.modules.settings.models.*');
		$model = new SettingsForm();
		if(isset($_POST['SettingsForm']))
		{
			$model->attributes = $_POST['SettingsForm'];
			if ($model->validate())
			{
				foreach($model->attributes as $key=>$value)
				{
					$category = $model->mapCategory($key);
					Settings::model()->set($category, $key, $value);
				}
				$this->redirect(array('administrator'));
			}
		}
		$this->render('sitesettings',array('model'=>$model));
	}
	
	public function actionAdministrator()
	{
		$model=new AdministratorForm;
		$model->setAttributes(array('fname' => 'Admin', 'sname' => 'OpenCMS'));
		if(isset($_POST['AdministratorForm']))
		{
			$model->attributes=$_POST['AdministratorForm'];
			if($model->validate())
			{
				$model->insertAdministrator();
				$this->redirect(array('finish'));
			}
		}
		$this->render('administrator',array('model'=>$model));
	}
	
	public function actionFinish()
	{
		file_put_contents(Yii::app()->basePath.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'installed', '');
		
		$this->render('finish');
	}
}